from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import mixins, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from goods.serializer import SKUSerializers
from . import constants
from .models import User
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from .serializers import CreateUserSerializers, UserDetailSerializers, EmailSerializer, BrowserSerializers
from . import serializers

# Create your views here.


# 判断用户名是否存在
class UserNameCountView(APIView):
    """用户名数量"""
    def get(self, request, username):
        """获取指定用户名数量,前端根据数量来判断是否存在"""
        count = User.objects.filter(username=username).count()
        return Response({
            'username': username,
            'count': count
        })


# 判断手机号是否存在
class MobileCountView(APIView):
    """手机号数量"""
    def get(self, request, mobile):
        """获取指定手机号数量,前端根据数量来判断是否存在"""
        count = User.objects.filter(mobile=mobile).count()

        # return Response({
        #     'username': mobile,
        #     'count': count
        # })

        data = {
            'username': mobile,
            'count': count
        }

        return Response(data)


class CreateUserView(CreateAPIView):
    """用户注册"""
    serializer_class = CreateUserSerializers


class UserDetailView(RetrieveAPIView):
    """
    用户个人信息
    GET /user/
    """

    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializers

    def get_object(self):
        # 返回的数据
        # 返回当前用户的对象
        return self.request.user


class EmailView(UpdateAPIView):
    """
    保存邮箱
    put /email/
    """

    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user


class VerifyEmailUrl(APIView):
    """
    邮箱激活链接
    get /email/verications/
    """
    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        # 解析token
        user = User.check_verify_email(token)
        if not user:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        # 判断是否是用户发送的
        else:

            # 是用户就修改邮箱状态
            user.email_active = True
            user.save()
            return Response({'message': 'ok'})


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class AddBrowserHistory(CreateAPIView):
    """保存历史浏览记录"""
    # 用户权限限制
    permission_classes = [IsAuthenticated]
    serializer_class = BrowserSerializers

    def get(self, request):
        """获取商品历史浏览记录"""
        # 获取当前用户的id
        user_id = request.user.id

        # 链接redis 获取数据
        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s'%user_id, 0, -1)

        skus = []
        for id in sku_ids:
            skus.append(SKU.objects.get(id=id))

        ser = SKUSerializers(skus, many=True)

        return Response(ser.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """登录"""

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            response = merge_cart_to_redis(request, user, response)

        return response
